package com.garlic.face.jlf.model;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.utils.Tools;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class Pay {
    private String TAG = this.getClass().getSimpleName();
    private Activity mActivity;
    private String mAuthCode = "", mScene = "", mAmount = "", mDownTradeNo = "";
    private PayListener mPayListener;
    private AuthBean mAuthBean;
    private Dialog mProgressDialog;
    private String mGoodsDetails = "";
    private String mSign;

    private void showProgress() {
        hideProgress();

        View root = View.inflate(mActivity, R.layout.garlic_general_loading_dialog, null);
        ImageView spaceshipImage = (ImageView) root.findViewById(R.id.img);
        TextView mProgressDialogMessage = (TextView) root.findViewById(R.id.tipTextView);// 提示文字
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                mActivity, R.anim.garlic_general_progress_rotate);
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        mProgressDialogMessage.setText("用户支付中,请稍候...");

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity).setView(root)
                .setCancelable(false);
        mProgressDialog = builder.create();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }

    private void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    public Pay(Activity a) {
        mActivity = a;
        this.mPayListener = null;
        this.mAmount = "";
        this.mScene = "";
        this.mAuthCode = "";
        this.mDownTradeNo = "";
        this.mSign = "";
        // this.mAuthBean = App.getUserInfo();

    }

    public interface PayListener {
        void onStart();

        void onSuccess(String result);

        void onError(String msg);
    }

    private PayListener defaultPayListener = new PayListener() {
        @Override
        public void onStart() {
            Log.e(TAG, "pay on start");
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showProgress();
                    if (mPayListener != null) {
                        mPayListener.onStart();
                    }
                }
            });


        }

        @Override
        public void onSuccess(final String result) {
            Log.e(TAG, "pay on success: " + result);
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgress();
                    if (mPayListener != null) {
                        mPayListener.onSuccess(result);
                    }
                }
            });

        }

        @Override
        public void onError(final String msg) {
            Log.e(TAG, "pay on error" + msg);
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    hideProgress();
                    if (mPayListener != null) {
                        mPayListener.onError(msg);
                    }
                }
            });

        }
    };

    public void setOnPayListener(PayListener l) {
        this.mPayListener = l;
    }

    // 生成订单号...
    private String genOrderNo() {
        Date today = new Date();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINESE);
        String trade_no = sdformat.format(today);
        int min = 11111111;
        int max = 99999999;
        Random random = new Random();
        int num = random.nextInt(max) % (max - min + 1) + min;
        return trade_no + num;
    }


    public void startPay(String auth_token, String amount, String scene, String detail_list,
                         String trade_No, String sign) {
        this.defaultPayListener.onStart();

        this.mSign = sign;
        this.mAuthCode = auth_token;
        this.mAmount = amount;
        this.mScene = scene;
        this.mDownTradeNo = genOrderNo();
        if (TextUtils.isEmpty(mAuthCode)) {
            this.defaultPayListener.onError("支付失败:授权码不合法");
            return;
        } else if (TextUtils.isEmpty(mScene) || (!mScene.equals("bar_code") && !mScene.equals
                ("security_code"))) {
            this.defaultPayListener.onError("支付失败:支付场景不合法");
            return;
        } else if (!Tools.checkPrice(this.mAmount)) {
            this.defaultPayListener.onError("支付失败:金额格式不合法");
            return;
        }

        List<GoodsBean> goodsBeans = new ArrayList<>();
        List<GoodsItem> list = JSON.parseArray(detail_list, GoodsItem.class);
        for (GoodsItem bean : list) {
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setBody(bean.getGoods_name());
            goodsBean.setGoods_categ(bean.getCategory_desc());
            goodsBean.setGoods_id(bean.getGoods_id());
            goodsBean.setGoods_name(bean.getGoods_name());
            goodsBean.setPrice(Tools.fen2yuan(bean.getCurrent_price() + ""));
            goodsBean.setQuantity(bean.getItem_count() + "");
            goodsBean.setShow_url("");

            goodsBeans.add(goodsBean);
        }

        this.mGoodsDetails = JSON.toJSONString(goodsBeans);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //异步线程中处理业务逻辑..
                try {
                    micropay();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                    loop(3);
                }
            }
        }).start();
    }

    private int getCurrentDelay(int i) {
        if (i < 10) {
            return 3000;
        } else {
            return 5000;
        }
    }

    private void micropay() throws Throwable {
        String url_pay = App.getPayPrefixUrl() + "miaofu/api/alipay/pay/micropay/" + this
                .mAuthBean.getStore_code();
        RequestParams params = new RequestParams(url_pay);
        params.addParameter("auth_code", this.mAuthCode);
        params.addParameter("fee", mAmount);
        params.addParameter("pay_scene", this.mScene);
        params.addParameter("DownTradeNo", this.mDownTradeNo);
        params.addParameter("terminalId", Tools.getDeviceNum());
        params.addParameter("pid", "2088131412771667");
        params.addParameter("goods_detail", this.mGoodsDetails);
        params.addParameter("terminal_params", this.mSign);

        String response = x.http().postSync(params, String.class);
        if (TextUtils.isEmpty(response)) {
            loop(3);
            return;
        }

        BaseBean bean = new BaseBean();
        bean.parse(response);

        if (bean.getCode().equals("-1")) {
            this.defaultPayListener.onError(bean.getMsg());
        } else if (bean.getCode().equals("1")) {
            loop(3);
        } else if (bean.getCode().equals("0")) {
            Log.e(TAG, bean.getData());
            TradeBean tradeBean = JSON.parseObject(bean.getData(), TradeBean.class);
            if (tradeBean.getTrade_status().equals("SUCCESS")) {
                //支付成功...
                this.defaultPayListener.onSuccess(bean.getData());
                return;
            }
        } else {
            loop(3);
        }
    }

    private String query() throws Throwable {
        RequestParams params = new RequestParams("http://www.miaofutech" +
                ".com/miaofu/api/alipay/pay/query/" + this.mAuthBean.getStore_code());
        params.addParameter("order", this.mDownTradeNo);
        params.addParameter("order_type", "2");
        return x.http().postSync(params, String.class);
    }

    private String reverse() throws Throwable {
        RequestParams params = new RequestParams("http://www.miaofutech" +
                ".com/miaofu/api/alipay/pay/reverse/" + this.mAuthBean.getStore_code());
        params.addParameter("order", this.mDownTradeNo);
        params.addParameter("order_type", "2");
        return x.http().postSync(params, String.class);
    }

    private void loop(int second) {
        for (int i = 0; i < 15; i++) {
            try {
                if (second == 0) {
                    Thread.sleep(getCurrentDelay(i));
                } else {
                    Thread.sleep(second * 1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //做查询....
            try {
                String response = query();
                Log.e(TAG, response);
                if (TextUtils.isEmpty(response)) {
                    continue;
                }

                BaseBean bean = new BaseBean();
                bean.parse(response);

                if (bean.getCode().equals("-1")) {
                    this.defaultPayListener.onError(bean.getMsg());
                    return;
                } else if (bean.isOk()) {
                    //检查代码
                    TradeBean tradeBean = JSON.parseObject(bean.getData(), TradeBean.class);
                    if (tradeBean.getTrade_status().equals("SUCCESS")) {
                        //支付成功...
                        this.defaultPayListener.onSuccess(bean.getData());
                        return;
                    }
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        //能走到这里..说明循环走完了...需要执行撤单..
        try {
            String response = reverse();
            Log.e(TAG, response);
            if (TextUtils.isEmpty(response)) {
                this.defaultPayListener.onError("撤单失败");
                return;
            }

            BaseBean bean = new BaseBean();
            bean.parse(response);

            if (bean.getCode().equals("-1")) {
                this.defaultPayListener.onError(bean.getMsg());
            } else if (bean.isOk()) {
                //检查代码
                this.defaultPayListener.onError("支付失败:撤单成功");
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            this.defaultPayListener.onError("撤单失败");
        }
    }
}
